from flask import Flask, jsonify, send_file, request
from flask_cors import CORS
import os
from pathlib import Path
from datetime import datetime
import threading
import mimetypes
import re

'''
要在 core/stream_manager.py 中
__init__ 加上：
        # 添加Web服务
        # from src.services.web_server import VideoWebServer
        # self.web_server = VideoWebServer(config_loader)
start 加上：
        # 启动Web服务
        # self.web_server.start()
stop 加上：
        # # 停止Web服务
        # if hasattr(self, 'web_server'):
        #     self.web_server.stop()
依赖
        # Web服务
        Flask>=2.3.3
        flask-cors>=4.0.0

'''
class VideoWebServer:
    def __init__(self, config_loader, host='0.0.0.0', port=5000):
        self.app = Flask(__name__)
        CORS(self.app)  # 允许跨域访问

        self.config = config_loader.get_app_config()
        self.video_path = Path(self.config['recording']['output_path'])
        self.host = host
        self.port = port
        self.server_thread = None

        # 注册路由
        self._register_routes()

    def _register_routes(self):
        """注册API路由"""

        @self.app.route('/api/videos', methods=['GET'])
        def get_video_list():
            """获取视频列表"""
            try:
                videos = []

                # 扫描视频目录
                for video_file in self.video_path.glob('*.mp4'):
                    # 获取文件信息
                    stat = video_file.stat()

                    # 解析文件名获取时间（假设格式：danger_20231225_143052.mp4）
                    filename = video_file.name
                    parts = filename.split('_')
                    if len(parts) >= 3:
                        date_str = parts[1]
                        time_str = parts[2].replace('.mp4', '')

                        # 格式化显示时间
                        try:
                            dt = datetime.strptime(f"{date_str}_{time_str}", "%Y%m%d_%H%M%S")
                            display_time = dt.strftime("%Y-%m-%d %H:%M:%S")
                        except:
                            display_time = filename
                    else:
                        display_time = filename

                    videos.append({
                        'id': video_file.stem,  # 文件名不带扩展名
                        'filename': filename,
                        'path': str(video_file),
                        'size': stat.st_size,
                        'size_mb': round(stat.st_size / 1024 / 1024, 2),
                        'created_time': stat.st_ctime,
                        'display_time': display_time,
                        'url': f'/api/video/{filename}'
                    })

                # 按创建时间倒序排序
                videos.sort(key=lambda x: x['created_time'], reverse=True)

                return jsonify({
                    'success': True,
                    'count': len(videos),
                    'videos': videos
                })

            except Exception as e:
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500

        @self.app.route('/api/video/<filename>', methods=['GET'])
        def get_video(filename):
            """获取视频文件流"""
            print(f"视频文件名：{filename}")
            try:
                video_path = self.video_path / filename

                if not video_path.exists():
                    return jsonify({
                        'success': False,
                        'error': 'Video not found'
                    }), 404

                # 获取Range请求头，支持视频seek
                range_header = request.headers.get('range', None)

                if range_header:
                    # 处理Range请求
                    return self._serve_video_range(video_path, range_header)
                else:
                    # 返回整个文件
                    return send_file(
                        video_path,
                        mimetype='video/mp4',
                        as_attachment=False,
                        download_name=filename
                    )

            except Exception as e:
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500

        @self.app.route('/api/delete/<filename>', methods=['DELETE'])
        def delete_video(filename):
            """删除视频文件"""
            try:
                video_path = self.video_path / filename

                if video_path.exists():
                    video_path.unlink()
                    return jsonify({
                        'success': True,
                        'message': f'Video {filename} deleted'
                    })
                else:
                    return jsonify({
                        'success': False,
                        'error': 'Video not found'
                    }), 404

            except Exception as e:
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500

        @self.app.route('/api/status', methods=['GET'])
        def get_status():
            """获取系统状态"""
            return jsonify({
                'success': True,
                'status': 'running',
                'video_count': len(list(self.video_path.glob('*.mp4')))
            })

    def _serve_video_range(self, video_path, range_header):
        """处理视频Range请求（支持seek）"""
        from flask import Response

        # 解析Range头
        byte_start = 0
        byte_end = None

        if range_header:
            match = re.search(r'bytes=(\d+)-(\d*)', range_header)
            if match:
                byte_start = int(match.group(1))
                if match.group(2):
                    byte_end = int(match.group(2))

        # 获取文件大小
        file_size = video_path.stat().st_size

        if byte_end is None:
            byte_end = file_size - 1

        # 读取指定范围的数据
        chunk_size = byte_end - byte_start + 1

        def generate():
            with open(video_path, 'rb') as f:
                f.seek(byte_start)
                remaining = chunk_size

                while remaining > 0:
                    to_read = min(4096, remaining)
                    data = f.read(to_read)
                    if not data:
                        break
                    remaining -= len(data)
                    yield data

        # 构建响应
        response = Response(
            generate(),
            status=206,  # Partial Content
            mimetype='video/mp4',
            content_type='video/mp4',
            direct_passthrough=True
        )

        # 设置响应头
        response.headers.add('Content-Range', f'bytes {byte_start}-{byte_end}/{file_size}')
        response.headers.add('Accept-Ranges', 'bytes')
        response.headers.add('Content-Length', str(chunk_size))

        return response

    def start(self):
        """启动Web服务器"""

        def run_server():
            self.app.run(host=self.host, port=self.port, debug=False, threaded=True)

        self.server_thread = threading.Thread(target=run_server)
        self.server_thread.daemon = True
        self.server_thread.start()

        print(f"[Web服务] 已启动在 http://{self.host}:{self.port}")
        print(f"[Web服务] API地址: http://{self.host}:{self.port}/api/videos")

    def stop(self):
        """停止Web服务器"""
        # Flask没有优雅的停止方法，这里只是标记
        print("[Web服务] 已停止")
